// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
//   2013 Petar Maymounkov <p@gocircuit.org>

package ns

import (
	"io"
	"os"
	"reflect"
	"strconv"
	"sync"
	"unicode"

	"circuit/kit/lang"
)

func uid() string {
	return strconv.Itoa(os.Getuid())
}

func gid() string {
	return strconv.Itoa(os.Getgid())
}

func valueHash(recv reflect.Value) uint64 {
	return uint64(lang.ComputeReceiverID(recv.Interface()))
}

func interfaceHash(recv interface{}) uint64 {
	return valueHash(reflect.ValueOf(recv))
}

func filename(n string) string {
	var m = []byte(n)
	m[0] = byte(unicode.ToLower(rune(m[0])))
	return string(m)
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//
type syncReader struct {
	sync.Mutex
	io.Reader
}

func (x *syncReader) Read(p []byte) (int, error) {
	x.Lock()
	defer x.Unlock()
	return x.Reader.Read(p)
}

//
type syncWriter struct {
	sync.Mutex
	io.Writer
}

func (x *syncWriter) Write(p []byte) (int, error) {
	x.Lock()
	defer x.Unlock()
	return x.Writer.Write(p)
}

//
type readWriteCloser struct {
	io.ReadCloser
	io.WriteCloser
}

func (rwc *readWriteCloser) Close() error {
	rwc.ReadCloser.Close()
	rwc.WriteCloser.Close()
	return nil
}
